package com.frame.imageprocess.strategy;


import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class BusinessLicenseStrategy implements ParsePicStrategy{

    private String params;

    public BusinessLicenseStrategy(String params) {
        this.params = params;
    }

    @Override
    public Map<String,String> parsePicSave(String params) {
        String url = params;
        try {
            // 使用 HttpClient 获取图片数据
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            byte[] imageData = EntityUtils.toByteArray(entity);
            // 将图片数据保存为临时文件
            File tempFile = File.createTempFile("tempImage", ".jpg");
            try (OutputStream os = new FileOutputStream(tempFile)) {
                os.write(imageData);
            }
            // 使用 Tesseract 进行 OCR
            Tesseract tesseract = new Tesseract();
            tesseract.setDatapath("E:\\zh");
            tesseract.setLanguage("chi_sim");
            String msg = tesseract.doOCR(tempFile).replace("\n", "").replace(" ", "");
            int startIndex = msg.indexOf("名称") + "名称".length();
            int endIndex = msg.indexOf("注册资本");
            String name = msg.substring(startIndex, endIndex).trim();
            int startIndex1 = msg.indexOf("法定代表人") + "法定代表人".length();
            int endIndex1 = msg.indexOf("营业期限");
            String name1 = msg.substring(startIndex1, endIndex1).trim();
            System.err.println("提取的名称：" + name);
            System.err.println("提取的法人：" + name1);
            response.close();
            httpClient.close();
            HashMap<String, String> map = new HashMap<>();
            map.put("name",name);
            map.put("name1",name1);
            return map;
        } catch (IOException | TesseractException e) {
            e.printStackTrace();
            return null;
        }
    }
}

